package com.wangan;

import com.lowagie.text.Image;
import org.jsoup.internal.StringUtil;
import org.w3c.dom.Element;
import org.xhtmlrenderer.extend.ReplacedElement;
import org.xhtmlrenderer.extend.ReplacedElementFactory;
import org.xhtmlrenderer.extend.UserAgentCallback;
import org.xhtmlrenderer.layout.LayoutContext;
import org.xhtmlrenderer.pdf.ITextFSImage;
import org.xhtmlrenderer.pdf.ITextImageElement;
import org.xhtmlrenderer.render.BlockBox;
import org.xhtmlrenderer.simple.extend.FormSubmissionListener;

import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;

public class ReplacedElementFactoryImpl implements ReplacedElementFactory {
    ITextImageElement createImageElement(String src, int cssWidth, int cssHeight) {
        String current = System.getProperty("user.dir");
        File file = Paths.get(current, "..", src).toFile();
        if (!file.exists()) {
            System.out.println(
                    String.format("file not exist,src=%s,file=%s", src, file.getAbsolutePath())
            );
            return null;
        }

        System.out.println(
                String.format("file=%s,width=%d,height=%d", file.getAbsolutePath(), cssWidth, cssHeight)
        );

        try {
            Image image = Image.getInstance(file.getAbsolutePath());

            System.out.println(
                    String.format(
                            "src image info,width=%s,height=%s", image.getWidth(), image.getHeight()
                    )
            );

            ITextFSImage iTextFSImage = new ITextFSImage(image);
            if (cssWidth != -1 || cssHeight != -1) {
                iTextFSImage.scale(cssWidth, cssHeight);
            }

            System.out.println(
                    String.format(
                            "itext image,width=%s,height=%s", iTextFSImage.getWidth(), iTextFSImage.getHeight()
                    )
            );

            return new ITextImageElement(iTextFSImage);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public ReplacedElement createReplacedElement(LayoutContext c, BlockBox box, UserAgentCallback uac, int cssWidth, int cssHeight) {
        Element element = box.getElement();
        String name = element.getNodeName();
        if (name.equalsIgnoreCase("img")) {
            String src = element.getAttribute("src");
            if (StringUtil.isBlank(src)) {
                return null;
            }
            return this.createImageElement(src, cssWidth, cssHeight);
        }
        return null;
    }

    @Override
    public void reset() {

    }

    @Override
    public void remove(Element e) {

    }

    @Override
    public void setFormSubmissionListener(FormSubmissionListener listener) {

    }
}
